package com.itheima.tanhua.dubbo.api;

import com.itheima.tanhua.model.domain.PageResult;
import com.itheima.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询今日佳人
     *
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser findWithMaxScore(Long toUserId) {
        //1.根据toUserId查询，根据评分score排序，获取第一条
        //构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //构建Query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        //调用mongoTemplate查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        return recommendUser;
    }

    @Override
    public PageResult findUserByPage(Integer page, Integer pagesize, Long toUserId) {

        Query query = Query.query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);

        long count = mongoTemplate.count(query, RecommendUser.class);

        return new PageResult(page,pagesize, (int) count,recommendUsers);

    }
}
